#include <ESP8266.h>
#ifdef ESP8266_USE_SOFTWARE_SERIAL
SoftwareSerial ser1(A0, A1);    
#else
#define ser1 Serial1
#endif
int i = 0;
int j = 0;
byte b_r[256] = {0};
byte b_t[256] = {0};
int len = 1024;
long t = 0;
#define b
#ifdef b
#define baud 9600
#else
#define baud 115200
#endif

void help() {
  Serial.println("HELP:");
  Serial.println("1.reset ESP8266 (AT+RST);");
  Serial.println("2.version (AT+GMR);");
  Serial.println("3.ap list (AT+CWLAP);");
  Serial.println("4.login (AT+CWJAP=\"ssid\",\"pwd\");");
  Serial.println("5.show wifi info (AT+CWJAP?);");
  Serial.println("6.show ip (AT+CIFSR);");
  Serial.println("7.exit wifi (AT+CWQAP);");
  Serial.println("8.set baud = 9600   (AT+CIOBAUD=9600);");
  Serial.println("9.set baud = 115200 (AT+CIOBAUD=115200);");
  Serial.println("a.AirKiss (AT+CWSMARTSTART=2);");
  Serial.println("h.help info;");
  Serial.println("input:");
}

void setup() {
  ser1.begin(baud);
  Serial.begin(baud);
  help();
}

void setBaud(long i_b){
  ser1.begin(i_b);
  Serial.begin(i_b);
  help();    
}

void loop() {
  delay(100);
#ifdef ESP8266_USE_SOFTWARE_SERIAL
  ser1.listen();
#endif
  j = ser1.available();
  while (j > 0) {
    b_r[i] = ser1.read();
    i++;
    if (i >= len) i = 0;
    j--;
  }
  if (i > 0) {
    j = 0;
    while (j < i) {
      Serial.write(b_r[j]);
      j++;
    }
    i = 0;
  }
  j = Serial.available();
  while ( j > 0) {
    b_t[i] = Serial.read();
    i++;
    if ( i >= len ) i = 0;
    j--;
  }

  if (i > 0) {
    char c = b_t[0];
    switch (c) {
      case 'h':
        help();
        break;
      case '1':
        ser1.print("AT+RST");
        ser1.print("\r\n");
        break;
      case '2':
        ser1.print("AT+GMR");
        ser1.print("\r\n");
        break;
      case '3':
        ser1.print("AT+CWLAP");
        ser1.print("\r\n");
        break;
      case '4':
        Serial.println("AT+CWJAP=\"ssid\",\"pwd\"");
        break;
      case '5':
        ser1.print("AT+CWJAP?");
        ser1.print("\r\n");
        break;
      case '6':
        ser1.print("AT+CIFSR");
        ser1.print("\r\n");
        break;
      case '7':
        ser1.print("AT+CWQAP");
        ser1.print("\r\n");
        break;
      case '8':
        ser1.print("AT+CIOBAUD=9600");
        ser1.print("\r\n");
        setBaud(9600);
        break;
      case '9':
        ser1.print("AT+CIOBAUD=115200");
        ser1.print("\r\n");
        setBaud(115200);
        break;
      case 'a':
        ser1.print("AT+CWSMARTSTART=2");
        ser1.print("\r\n");
        break;
      default:
        j = 0;
        while (j < i) {
          ser1.write(b_t[j]);
          j++;
        }
        i = 0;
        t = millis();
    }
  }

  if (t > 0 && millis() - t > 100) {
    ser1.write(char(13));
    ser1.write(char(10));
    t = 0;
  }
}
